import React from 'react'
import {connect,} from 'react-redux'
import GoBackLayout from "../../layouts/GoBackLayout/GoBackLayout"
import TabWithCustomUnderline from "../../layouts/TabWithCustomUnderline/TabWithCustomUnderline"
import './game-filter.css'
import {formatDate, handleDateChange} from "../../utils/dateService";
import {withRouter,} from 'react-router-dom'
import Pinyin from "../../utils/pinyin";
import BtnSortedByPinyin from "./BtnSortedByPinyin/BtnSortedByPinyin";
import {goBack} from "../../utils/goback";


class GameFilter extends React.Component {

    constructor(props) {
        super(props)
        this.today = this.props.game.today
        this.tabPostion = this.props.tabPosition
        this.games = this.props.game.games
        this.state = {
            tabData: [],
        }
    }


    componentDidMount() {

        const today = this.today
        const curP1 = this.tabPostion[1]
        const curP2 = this.tabPostion[2]
        let date
        if (curP1 === 0 || curP1 === 1) {
            date = today
        } else {
            if (curP1 === 2) {
                let diff = curP2.schedule
                date = formatDate(handleDateChange(today, diff))
            } else if (curP1 === 3) {
                let diff = curP2.result - 3
                date = formatDate(handleDateChange(today, diff))
            }
        }
        const events = this.games[date].events
        const matches = this.games[date].matches
        const notStartedMatches = matches.filter(match => match[2] === 1)
        const onLiveMatches = matches.filter(match => match[2] > 1 && match[2] < 8)
        const endedMatches = matches.filter(match => match[2] === 8)
        let notStatedEvents = {}
        let onLiveEvents = {}
        let endedEvents = {}
        let allEvents = {}
        notStartedMatches.map(match => {
            // if (ma)
            const eventId = match[1]
            notStatedEvents[eventId] = events[eventId]
            allEvents[eventId] = events[eventId]
        })
        onLiveMatches.map(match => {
            // if (ma)
            const eventId = match[1]
            onLiveEvents[eventId] = events[eventId]
            allEvents[eventId] = events[eventId]
        })
        endedMatches.map(match => {
            // if (ma)
            const eventId = match[1]
            endedEvents[eventId] = events[eventId]
            allEvents[eventId] = events[eventId]
        })
        let eventsToRender
        if (curP1 === 0) {
            eventsToRender = allEvents
        } else if (curP1 === 1) {
            eventsToRender = onLiveEvents
        } else if (curP1 === 2 ) {
            eventsToRender = notStatedEvents
        } else if (curP1 === 3) {
            eventsToRender = endedEvents
        }

        // console.log(notStatedEvents, onLiveEvents, endedEvents)

        if (Object.keys(events).length <= 1) {
            this.props.doFetchGameListAll({date,})
        }
        this.setState({
            tabData: Object.entries(eventsToRender).map(data => {
                const events = this.props.game.eventFilters
                let active = true
                if (events.length > 0) {
                    active = events.findIndex(e => e.id === data[0]) > -1
                }
                return {
                    id: data[0],
                    value: data[1],
                    active: active,
                }
            }),
        })
        // this.props.doFetchGameListAll({date: today,})
        // this.props.doFetchEventList()
    }


    componentDidUpdate(prevProps, prevState, snapshot) {
        const {
            today: prevToday,
            games: prveGames
        } = prevProps.game
        const {
            today,
            games,
        } = this.props.game
        const prevEventsArr = Object.entries(prveGames[prevToday].events)
        const eventsArr = Object.entries(games[today].events)
        if (prevEventsArr.length !== eventsArr.length) {
            const arr = []
            eventsArr.map(event => arr.push({id: event[0], value: event[1], active: false,}))

            this.setState({
                tabData: arr,
            })
        }
    }

    selectOneGame = (e, itemToSelect) => {
        const arr = [...this.state.tabData]
        // setCurrentData(arr)
        const i = arr.findIndex(item => item.id === itemToSelect.id)
        arr[i].active = !arr[i].active
        this.setState({
            tabData: arr,
        })
    }

    selectAll = () => {
        const arr = [...this.state.tabData]
        arr.forEach(item => item.active = true)
        this.setState({tabData: arr})
    }

    reverseAll = () => {
        const arr = [...this.state.tabData]
        arr.forEach(item => item.active = !item.active)
        this.setState({tabData: arr})
    }

    changeFilter = (arr) => {

        const eventFilters = [...arr].filter(event => event.active === true)
        if (eventFilters.length !== arr.length) {
            this.props.changeEventFilter({eventFilters,})
        }
        if (arr.every(event => event.active === true)) {
            this.props.changeEventFilter({eventFilters: [],})
        }
        goBack(this.props.history)
    }

    render() {

        const {history} = this.props
        // console.log(game)

        const sortedBtn = [...this.state.tabData]
            .map(btn => {
                const btnPy = new Pinyin(btn.value.short_name_zh)
                btn.pinyin = btnPy.getFullChars()
                return btn
            })
            .sort((a, b) => {
                if (a.pinyin[0] < b.pinyin[0]) {
                    return -1
                } else if (a.pinyin[0] === b.pinyin[0]) {
                    return 1
                } else {
                    return 0
                }
            })

        let sortedByPinyin = {}

        // eslint-disable-next-line array-callback-return
        sortedBtn.map(btn => {
            let first = btn.pinyin[0]
            if (sortedByPinyin[first]) {
                sortedByPinyin[first].push(btn)
            } else {
                sortedByPinyin[first] = [btn]
            }
        })

        // const btns = sortedBtn.map(event => {
        //     const id = event.id
        //     const value = event.value
        //     const active = event.active
        //     // let pinyin = new Pinyin(value.short_name_zh)
        //     // console.log(pinyin.getFullChars())
        //
        //     return <ClickableBtn
        //         key={id}
        //         active={`${active}`}
        //         onClick={(e) => this.selectOneGame(e, event)}
        //     >
        //         {/*{item.title}*/}
        //         {value.short_name_zh}
        //     </ClickableBtn>
        // })
        // const tabs =
        // const [currentTab, setCurrentTab] = useState(tabs[0])
        // const [currentData, setCurrentData] = useState(data)


        return <GoBackLayout
            history={history}
            title='赛事选择'
        >
            {/*<TabWithCustomUnderline*/}
            {/*    tabs={this.tabs}*/}
            {/*    tabBarUnderlineStyle={{border: '1px solid #36C8B9', background: '#36C8B9'}}*/}
            {/*    // onChange={(tab, index) => this.setCurrentTab(tab)}*/}
            {/*    animated={false}*/}
            {/*>*/}
            {/*    */}
            {/*</TabWithCustomUnderline>*/}
            <BtnSortedByPinyin
                btns={this.state.tabData}
                selectOneGame={this.selectOneGame}
            />
            <div className='flex-center-align-center game-filter-bottom-btns'>

                <div className='flex-space-between-align-center game-filter-bottom-btn-left'>
                    <div onClick={this.selectAll}>
                        <span>全选</span>
                    </div>
                    <div onClick={this.reverseAll}>
                        <span>反选</span>
                    </div>
                </div>
                <div
                    className='game-filter-bottom-btn-right'
                    onClick={() => this.changeFilter(this.state.tabData)}
                >
                    <span>确定</span>
                </div>
            </div>

        </GoBackLayout>







        // console.log(currentData)


        // useEffect(() => {
        //     setTimeout(() => {
        //         const data = gameData[currentTab.title]
        //         const newData = data.map(item => ({value: item, active: false,}))
        //         setCurrentData(newData)
        //     }, 500)
        // }, [currentTab])

        // const selectOneGame = (e, itemToSelect) => {
        //     const arr = [...currentData]
        //     setCurrentData(arr)
        //     // const i = arr.findIndex(item => item.title === itemToSelect.title)
        //     // arr[i].active = !arr[i].active
        //     // setCurrentData(arr)
        // }



        // const dataTemplate = (currentData.map((item, index) => {
        //     console.log(item)
        //     return (
        //         <ClickableBtn
        //             key={index}
        //             active={`${item.active}`}
        //             onClick={(e) => selectOneGame(e, item)}
        //         >
        //             {/*{item.title}*/}
        //             {item[1].name_zh}
        //         </ClickableBtn>
        //     )
        // }))

        // const template = (
        //     <GoBackLayout
        //         history={history}
        //         title='赛事选择'
        //     >
        //         <TabWithCustomUnderline
        //             tabs={tabs}
        //             onChange={(tab, index) => setCurrentTab(tab)}
        //         >
        //
        //             <div className='game-filter-data-ctn'>
        //                 {dataTemplate}
        //             </div>
        //
        //         </TabWithCustomUnderline>

        //     </GoBackLayout>
        // )

        // return template
    }


}

const mapState = state => ({
    game: state.game,
    tabPosition: state.game.tabPosition,
})

const mapDispatch = dispatch => ({
    // doFetchEventList:
    doFetchGameListAll: (payload) => dispatch.game.doFetchGameListAll(payload),
    doFetchEventList: (payload) => dispatch.game.doFetchEventList(payload),
    changeEventFilter: (payload) => dispatch.game.changeEventFilter(payload)
})

export default connect(mapState, mapDispatch)(withRouter(GameFilter))
